{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# 函数参数的传递\n",
    "\n",
    "def print_log(func):\n",
    "    def inner(*args, **kw):\n",
    "        print('call %s():' % func.__name__)\n",
    "        func(*args, **kw)\n",
    "    return inner\n",
    "\n",
    "@print_log\n",
    "def func1():\n",
    "    print(\"hello\")\n",
    "\n",
    "func1()"
   ],
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {},
   "cell_type": "code",
   "source": [
    "# 被装饰的函数有返回值，装饰器应return 函数调用\n",
    "\n",
    "def print_log(func):\n",
    "    def inner(*args, **kw):\n",
    "        print('call %s():' % func.__name__)\n",
    "        return func(*args, **kw)\n",
    "    return inner\n",
    "\n",
    "@print_log\n",
    "def func1(a, b, c):\n",
    "    return a + b + c\n",
    "\n",
    "print(func1(10, 20 , 30))"
   ],
   "id": "4dc424046774ea68",
   "outputs": [],
   "execution_count": null
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-10-25T07:42:17.402990Z",
     "start_time": "2024-10-25T07:42:17.399807Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 装饰器有参数\n",
    "\n",
    "def print_log(_type):\n",
    "    print(_type)\n",
    "    def wrapper(func):\n",
    "        def inner(*args, **kw):\n",
    "            res = func(*args, **kw)\n",
    "            if _type == \"控制台\":\n",
    "                print(\"call %s():\" % func.__name__)\n",
    "            else:\n",
    "                print(\"打印日志到文件\")\n",
    "            return res\n",
    "        return inner\n",
    "    return wrapper\n",
    "\n",
    "\n",
    "@print_log(\"控制台\")\n",
    "def func1(a, b, c):\n",
    "    return a + b + c\n",
    "\n",
    "print(func1(10, 20 , 30))"
   ],
   "id": "123b178d88b41df8",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "控制台\n",
      "call func1():\n",
      "60\n"
     ]
    }
   ],
   "execution_count": 10
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
